<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>ActiveRecord::Transactions::ClassMethods</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />
<script src="../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>

</head>

<body>     
    <div class="banner">
        
            <span>Ruby on Rails v4.0.0</span><br />
        
        <h1>
            <span class="type">Module</span> 
            ActiveRecord::Transactions::ClassMethods 
            
        </h1>
        <ul class="files">
            
            <li><a href="../../../files/activerecord/lib/active_record/transactions_rb.html">activerecord/lib/active_record/transactions.rb</a></li>
            
        </ul>
    </div>
    <div id="bodyContent">
        <div id="content">
  
    <div class="description">
      
<h1 id="label-Active+Record+Transactions">Active Record <a href="../Transactions.html">Transactions</a></h1>

<p><a href="../Transactions.html">Transactions</a> are protective blocks where
SQL statements are only permanent if they can all succeed as one atomic
action. The classic example is a transfer between two accounts where you
can only have a deposit if the withdrawal succeeded and vice versa. <a
href="../Transactions.html">Transactions</a> enforce the integrity of the
database and guard the data against program errors or database break-downs.
So basically you should use transaction blocks whenever you have a number
of statements that must be executed together or not at all.</p>

<p>For example:</p>

<pre>ActiveRecord::Base.transaction do
  david.withdrawal(100)
  mary.deposit(100)
end</pre>

<p>This example will only take money from David and give it to Mary if neither
<code>withdrawal</code> nor <code>deposit</code> raise an exception.
Exceptions will force a ROLLBACK that returns the database to the state
before the transaction began. Be aware, though, that the objects will
<em>not</em> have their instance data returned to their pre-transactional
state.</p>

<h2 id="label-Different+Active+Record+classes+in+a+single+transaction">Different Active Record classes in a single transaction</h2>

<p>Though the transaction class method is called on some Active Record class,
the objects within the transaction block need not all be instances of that
class. This is because transactions are per-database connection, not
per-model.</p>

<p>In this example a <code>balance</code> record is transactionally saved even
though <code>transaction</code> is called on the <code>Account</code>
class:</p>

<pre>Account.transaction do
  balance.save!
  account.save!
end</pre>

<p>The <code>transaction</code> method is also available as a model instance
method. For example, you can also do this:</p>

<pre>balance.transaction do
  balance.save!
  account.save!
end</pre>

<h2 id="label-Transactions+are+not+distributed+across+database+connections"><a href="../Transactions.html">Transactions</a> are not distributed across database connections</h2>

<p>A transaction acts on a single database connection. If you have multiple
class-specific databases, the transaction will not protect interaction
among them. One workaround is to begin a transaction on each class whose
models you alter:</p>

<pre>Student.transaction do
  Course.transaction do
    course.enroll(student)
    student.units += course.units
  end
end</pre>

<p>This is a poor solution, but fully distributed transactions are beyond the
scope of Active Record.</p>

<h2 id="label-save+and+destroy+are+automatically+wrapped+in+a+transaction"><code>save</code> and <code>destroy</code> are automatically wrapped in a transaction</h2>

<p>Both <code>save</code> and <code>destroy</code> come wrapped in a
transaction that ensures that whatever you do in validations or callbacks
will happen under its protected cover. So you can use validations to check
for values that the transaction depends on or you can raise exceptions in
the callbacks to rollback, including <code>after_*</code> callbacks.</p>

<p>As a consequence changes to the database are not seen outside your
connection until the operation is complete. For example, if you try to
update the index of a search engine in <code>after_save</code> the indexer
won’t see the updated record. The <code>after_commit</code> callback is the
only one that is triggered once the update is committed. See below.</p>

<h2 id="label-Exception+handling+and+rolling+back">Exception handling and rolling back</h2>

<p>Also have in mind that exceptions thrown within a transaction block will be
propagated (after triggering the ROLLBACK), so you should be ready to catch
those in your application code.</p>

<p>One exception is the <code>ActiveRecord::Rollback</code> exception, which
will trigger a ROLLBACK when raised, but not be re-raised by the
transaction block.</p>

<p><strong>Warning</strong>: one should not catch
<code>ActiveRecord::StatementInvalid</code> exceptions inside a transaction
block. <code>ActiveRecord::StatementInvalid</code> exceptions indicate that
an error occurred at the database level, for example when a unique
constraint is violated. On some database systems, such as PostgreSQL,
database errors inside a transaction cause the entire transaction to become
unusable until it's restarted from the beginning. Here is an example which
demonstrates the problem:</p>

<pre class="ruby"><span class="ruby-comment"># Suppose that we have a Number model with a unique column called 'i'.</span>
<span class="ruby-constant">Number</span>.<span class="ruby-identifier">transaction</span> <span class="ruby-keyword">do</span>
  <span class="ruby-constant">Number</span>.<span class="ruby-identifier">create</span>(<span class="ruby-identifier">i</span><span class="ruby-operator">:</span> <span class="ruby-value">0</span>)
  <span class="ruby-keyword">begin</span>
    <span class="ruby-comment"># This will raise a unique constraint error...</span>
    <span class="ruby-constant">Number</span>.<span class="ruby-identifier">create</span>(<span class="ruby-identifier">i</span><span class="ruby-operator">:</span> <span class="ruby-value">0</span>)
  <span class="ruby-keyword">rescue</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">StatementInvalid</span>
    <span class="ruby-comment"># ...which we ignore.</span>
  <span class="ruby-keyword">end</span>

  <span class="ruby-comment"># On PostgreSQL, the transaction is now unusable. The following</span>
  <span class="ruby-comment"># statement will cause a PostgreSQL error, even though the unique</span>
  <span class="ruby-comment"># constraint is no longer violated:</span>
  <span class="ruby-constant">Number</span>.<span class="ruby-identifier">create</span>(<span class="ruby-identifier">i</span><span class="ruby-operator">:</span> <span class="ruby-value">1</span>)
  <span class="ruby-comment"># =&gt; &quot;PGError: ERROR:  current transaction is aborted, commands</span>
  <span class="ruby-comment">#     ignored until end of transaction block&quot;</span>
<span class="ruby-keyword">end</span>
</pre>

<p>One should restart the entire transaction if an
<code>ActiveRecord::StatementInvalid</code> occurred.</p>

<h2 id="label-Nested+transactions">Nested transactions</h2>

<p><code>transaction</code> calls can be nested. By default, this makes all
database statements in the nested transaction block become part of the
parent transaction. For example, the following behavior may be surprising:</p>

<pre>User.transaction do
  User.create(username: 'Kotori')
  User.transaction do
    User.create(username: 'Nemu')
    raise ActiveRecord::Rollback
  end
end</pre>

<p>creates both “Kotori” and “Nemu”. Reason is the
<code>ActiveRecord::Rollback</code> exception in the nested block does not
issue a ROLLBACK. Since these exceptions are captured in transaction
blocks, the parent block does not see it and the real transaction is
committed.</p>

<p>In order to get a ROLLBACK for the nested transaction you may ask for a
real sub-transaction by passing <code>requires_new: true</code>. If
anything goes wrong, the database rolls back to the beginning of the
sub-transaction without rolling back the parent transaction. If we add it
to the previous example:</p>

<pre>User.transaction do
  User.create(username: 'Kotori')
  User.transaction(requires_new: true) do
    User.create(username: 'Nemu')
    raise ActiveRecord::Rollback
  end
end</pre>

<p>only “Kotori” is created. This works on MySQL and PostgreSQL. SQLite3
version &gt;= ‘3.6.8’ also supports it.</p>

<p>Most databases don’t support true nested transactions. At the time of
writing, the only database that we’re aware of that supports true nested
transactions, is MS-SQL. Because of this, Active Record emulates nested
transactions by using savepoints on MySQL and PostgreSQL. See <a
href="http://dev.mysql.com/doc/refman/5.6/en/savepoint.html">dev.mysql.com/doc/refman/5.6/en/savepoint.html</a>
for more information about savepoints.</p>

<h3 id="label-Callbacks"><a href="../Callbacks.html">Callbacks</a></h3>

<p>There are two types of callbacks associated with committing and rolling
back transactions: <code>after_commit</code> and
<code>after_rollback</code>.</p>

<p><code>after_commit</code> callbacks are called on every record saved or
destroyed within a transaction immediately after the transaction is
committed. <code>after_rollback</code> callbacks are called on every record
saved or destroyed within a transaction immediately after the transaction
or savepoint is rolled back.</p>

<p>These callbacks are useful for interacting with other systems since you
will be guaranteed that the callback is only executed when the database is
in a permanent state. For example, <code>after_commit</code> is a good spot
to put in a hook to clearing a cache since clearing it from within a
transaction could trigger the cache to be regenerated before the database
is updated.</p>

<h3 id="label-Caveats">Caveats</h3>

<p>If you’re on MySQL, then do not use DDL operations in nested transactions
blocks that are emulated with savepoints. That is, do not execute
statements like ‘CREATE TABLE’ inside such blocks. This is because MySQL
automatically releases all savepoints upon executing a DDL operation. When
<code>transaction</code> is finished and tries to release the savepoint it
created earlier, a database error will occur because the savepoint has
already been automatically released. The following example demonstrates the
problem:</p>

<pre>Model.connection.transaction do                           # BEGIN
  Model.connection.transaction(requires_new: true) do  # CREATE SAVEPOINT active_record_1
    Model.connection.create_table(...)                    # active_record_1 now automatically released
  end                                                     # RELEASE savepoint active_record_1
                                                          # ^^^^ BOOM! database error!
end</pre>

<p>Note that “TRUNCATE” is also a MySQL DDL statement!</p>

    </div>
  


  


  
  


  


  
    <!-- Method ref -->
    <div class="sectiontitle">Methods</div>
    <dl class="methods">
      
        <dt>A</dt>
        <dd>
          <ul>
            
              
              <li>
                <a href="ClassMethods.html#method-i-after_commit">after_commit</a>,
              </li>
            
              
              <li>
                <a href="ClassMethods.html#method-i-after_rollback">after_rollback</a>
              </li>
            
          </ul>
        </dd>
      
        <dt>T</dt>
        <dd>
          <ul>
            
              
              <li>
                <a href="ClassMethods.html#method-i-transaction">transaction</a>
              </li>
            
          </ul>
        </dd>
      
    </dl>
  

  



  

    

    

    


    


    <!-- Methods -->
        
      <div class="sectiontitle">Instance Public methods</div>
      
        <div class="method">
          <div class="title method-title" id="method-i-after_commit">
            
              <b>after_commit</b>(*args, &amp;block)
            
            <a href="ClassMethods.html#method-i-after_commit" name="method-i-after_commit" class="permalink">Link</a>
          </div>
          
          
            <div class="description">
              <p>This callback is called after a record has been created, updated, or
destroyed.</p>

<p>You can specify that the callback should only be fired by a certain action
with the <code>:on</code> option:</p>

<pre>after_commit :do_foo, on: :create
after_commit :do_bar, on: :update
after_commit :do_baz, on: :destroy

after_commit :do_foo_bar, :on [:create, :update]
after_commit :do_bar_baz, :on [:update, :destroy]</pre>

<p>Note that transactional fixtures do not play well with this feature. Please
use the <code>test_after_commit</code> gem to have these hooks fired in
tests.</p>
            </div>
          
          
          
          
          
            
            <div class="sourcecode">
              
              <p class="source-link">
                Source: 
                <a href="javascript:toggleSource('method-i-after_commit_source')" id="l_method-i-after_commit_source">show</a>
                
                  | <a href="https://github.com/rails/rails/blob/9d2146ac6e4c1fdc9cc157d614b1eb9968ac6a2e/activerecord/lib/active_record/transactions.rb#L226" target="_blank" class="github_url">on GitHub</a>
                
              </p>
              <div id="method-i-after_commit_source" class="dyn-source">
                <pre><span class="ruby-comment"># File activerecord/lib/active_record/transactions.rb, line 226</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">after_commit</span>(*<span class="ruby-identifier">args</span>, &amp;<span class="ruby-identifier">block</span>)
  <span class="ruby-identifier">set_options_for_callbacks!</span>(<span class="ruby-identifier">args</span>)
  <span class="ruby-identifier">set_callback</span>(<span class="ruby-value">:commit</span>, <span class="ruby-value">:after</span>, *<span class="ruby-identifier">args</span>, &amp;<span class="ruby-identifier">block</span>)
<span class="ruby-keyword">end</span></pre>
              </div>
            </div>
            
          </div>
        
        <div class="method">
          <div class="title method-title" id="method-i-after_rollback">
            
              <b>after_rollback</b>(*args, &amp;block)
            
            <a href="ClassMethods.html#method-i-after_rollback" name="method-i-after_rollback" class="permalink">Link</a>
          </div>
          
          
            <div class="description">
              <p>This callback is called after a create, update, or destroy are rolled back.</p>

<p>Please check the documentation of <code>after_commit</code> for options.</p>
            </div>
          
          
          
          
          
            
            <div class="sourcecode">
              
              <p class="source-link">
                Source: 
                <a href="javascript:toggleSource('method-i-after_rollback_source')" id="l_method-i-after_rollback_source">show</a>
                
                  | <a href="https://github.com/rails/rails/blob/9d2146ac6e4c1fdc9cc157d614b1eb9968ac6a2e/activerecord/lib/active_record/transactions.rb#L234" target="_blank" class="github_url">on GitHub</a>
                
              </p>
              <div id="method-i-after_rollback_source" class="dyn-source">
                <pre><span class="ruby-comment"># File activerecord/lib/active_record/transactions.rb, line 234</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">after_rollback</span>(*<span class="ruby-identifier">args</span>, &amp;<span class="ruby-identifier">block</span>)
  <span class="ruby-identifier">set_options_for_callbacks!</span>(<span class="ruby-identifier">args</span>)
  <span class="ruby-identifier">set_callback</span>(<span class="ruby-value">:rollback</span>, <span class="ruby-value">:after</span>, *<span class="ruby-identifier">args</span>, &amp;<span class="ruby-identifier">block</span>)
<span class="ruby-keyword">end</span></pre>
              </div>
            </div>
            
          </div>
        
        <div class="method">
          <div class="title method-title" id="method-i-transaction">
            
              <b>transaction</b>(options = {}, &amp;block)
            
            <a href="ClassMethods.html#method-i-transaction" name="method-i-transaction" class="permalink">Link</a>
          </div>
          
          
            <div class="description">
              <p>See <a
href="ClassMethods.html">ActiveRecord::Transactions::ClassMethods</a> for
detailed documentation.</p>
            </div>
          
          
          
          
          
            
            <div class="sourcecode">
              
              <p class="source-link">
                Source: 
                <a href="javascript:toggleSource('method-i-transaction_source')" id="l_method-i-transaction_source">show</a>
                
                  | <a href="https://github.com/rails/rails/blob/9d2146ac6e4c1fdc9cc157d614b1eb9968ac6a2e/activerecord/lib/active_record/transactions.rb#L207" target="_blank" class="github_url">on GitHub</a>
                
              </p>
              <div id="method-i-transaction_source" class="dyn-source">
                <pre><span class="ruby-comment"># File activerecord/lib/active_record/transactions.rb, line 207</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">transaction</span>(<span class="ruby-identifier">options</span> = {}, &amp;<span class="ruby-identifier">block</span>)
  <span class="ruby-comment"># See the ConnectionAdapters::DatabaseStatements#transaction API docs.</span>
  <span class="ruby-identifier">connection</span>.<span class="ruby-identifier">transaction</span>(<span class="ruby-identifier">options</span>, &amp;<span class="ruby-identifier">block</span>)
<span class="ruby-keyword">end</span></pre>
              </div>
            </div>
            
          </div>
                    </div>

    </div>
  </body>
</html>    